<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/7/4
 * Time: 11:18 AM
 */
namespace app\common\models;

use Illuminate\Database\Eloquent\SoftDeletes;

class Department extends BaseModel
{
    public $table = 'yq_department';
    public $timestamps = true;
    protected $guarded = [''];
    use SoftDeletes;

    /*
     * 获取当前部门的所有上级部门ID
     */
    public function getAllDepartmentParentId($department_id_arr, $department_list = [])
    {
        $department_list = $department_list ?: self::site()->get();
        $this_parent_id_arr = $department_list->whereIn('id', $department_id_arr)->pluck('pid')->toArray();
        $parent_id_arr = $this_parent_id_arr = array_values(array_unique(array_filter($this_parent_id_arr)));

        if (!$parent_id_arr) {
            return [];
        }
        do {
            $this_parent_id_arr = $department_list->whereIn('id', $this_parent_id_arr)->pluck('pid')->toArray();
            $this_parent_id_arr = array_values(array_unique(array_filter($this_parent_id_arr)));
            $parent_id_arr = array_merge($parent_id_arr, $this_parent_id_arr);
        } while ($this_parent_id_arr);

        return array_values(array_unique(array_filter($parent_id_arr)));
    }
    /*
     * 获取当前部门的所有下级部门ID
     */
    public function getAllDepartmentSubId($department_id_arr, $department_list = [])
    {
        $department_list = $department_list ?: self::site()->get();
        $this_sub_id_arr = $department_list->whereIn('pid', $department_id_arr)->pluck('id')->toArray();
        $sub_id_arr = $this_sub_id_arr = array_values(array_unique(array_filter($this_sub_id_arr)));

        if (!$sub_id_arr) {
            return [];
        }

        do {
            if ($this_sub_id_arr = $department_list->whereIn('pid', $this_sub_id_arr)->pluck('id')->toArray()) {
                $sub_id_arr = array_merge($sub_id_arr, $this_sub_id_arr);
            }
        } while ($this_sub_id_arr);

        return array_values(array_unique(array_filter($sub_id_arr)));
    }
    public function parentDepartment()
    {
        return $this->hasOne(self::class, 'id', 'pid');
    }
    public function subDepartments()
    {
        return $this->hasMany(self::class, 'pid', 'id');
    }
    public function DepartmentAdminUsers()
    {
        return $this->hasMany(DepartmentAdminUser::class, 'department_id', 'id');
    }
    public  function atributeNames() {
        return [
            'name'  => '部门名称'
        ];
    }

    public  function rules()
    {
        return [
            'name' => 'required'
        ];
    }
}